import {Component, OnInit} from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {ResponseUtil} from "../../../../util/response-util";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {UsersService} from "../users.service";
import {User} from "../user";
import {MsgConstants, API} from "../../../../constants/constants";
import {MsgResult} from "../../../../models/msg-result";
import {Account} from "../../../permission/accounts/account";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../../util/page-subject";
import {TableUtil} from "../../../../util/table-util";

declare var $;
@Component({
  selector: 'app-user-assign-acc',
  templateUrl: './user-assign-acc.component.html'
})
export class UserAssignAccComponent implements OnInit {

  user: User;

  userId: string;

  userCode: string;

  accounts: Account[];

  table;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private responseUtil: ResponseUtil,
    private pageSubject: PageSubject,
    private tableUtil: TableUtil,
    private dialogService: OneDialogService,
    private usersService: UsersService
  ) {
  }

  ngOnInit() {
    //异步调用
    this.pushPage();
    //获取账户数据进行初始化
    this.initAccountFromData();
    //获取数据
    if (!!this.route.snapshot.params["userId"]) {
      this.userId = this.route.snapshot.params["userId"];
    }
  }

  /**
   * 搜索
   */
  search() {
    this.table.bootstrapTable('refresh');
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("用户系统", "");
    this.pageSubject.pushPage("用户管理", "分配账户", path);
  }

  /**
   * 分配账户
   */
  saveAllocationAccount() {
    let rows = this.table.bootstrapTable('getSelections');
    if (!rows[0]) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.userCode = this.tableUtil.getCloumn(rows[0], "accountName");
      let accountId = this.tableUtil.getCloumn(rows[0], "id");
      if (!!this.userCode) {
        this.usersService.updateUserForAssignAcc(this.userId, this.userCode, accountId).subscribe(
          result => this.responseUtil.success(result, this.processAssignAccountResult),
          message => this.responseUtil.error(message)
        );
      } else {
        this.dialogService.modalInfo("请选择一条数据");
      }
    }
  }

  /**
   * 对分配账户结果进行处理
   */
  private processAssignAccountResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.modalSuccess("分配账户成功！", () => this.createAccountSuccess());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  private createAccountSuccess() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }

  /**
   * 创建账户
   */
  createAccount() {
    this.router.navigate(['../creat', {id: this.userId}], {relativeTo: this.route});
  }

  /**
   * 取消分配账户(上一步)
   */
  cancelAllocationAccount() {
    this.router.navigate(['../add', {userid: this.userId}], {relativeTo: this.route});
  }

  /**
   *
   初始化账户表单
   * @param datas
   */
  initAccountFromData() {
    this.table = this.tableUtil.load('customer-account',{
      columns: [
        {
          field: ' ',
          checkbox: true,
        }, {
          field: "id",
          title: 'ID',
          align: 'left',
          visible: false,
          switchable: false
        }, {
          field: 'accountName',
          title: '账户',
          align: "left",
          halign: "center"
        }, {
          field: 'creator',
          title: '创建人',
          align: "left",
          halign: "center"
        }, {
          field: 'CREATE_DATE',
          title: '创建日期',
          align: "left",
          halign: "center",
          sortName: "CREATE_DATE", sortable: true
        }, {
          field: 'isAllowPc',
          title: 'PC端登录',
          align: "left",
          halign: "center",
          formatter: this.yesOrNoFormat
        }, {
          field: 'isAllowApp',
          title: '移动端登录',
          align: "left",
          halign: "center",
          formatter: this.yesOrNoFormat
        }, {
          field: 'isAudit',
          title: '审核',
          align: "left",
          halign: "center",
          formatter: this.yesOrNoFormat
        }, {
          field: 'isEnable',
          title: '启用',
          formatter: this.yesOrNoFormat
        }
      ],
      idField: "id",
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 25, 50, 100],
      paginationPreText: "上一页",
      paginationNextText: "下一页",
      paginationLoop: false,//是否开启循环分页
      singleSelect: true,//单选
      clickToSelect: true,//点击选中
      toolbar: "#one_operation_user-assign-acc",
      url: API.accountPageListV2,
      method: 'post',
      //传递附加参数
      queryParams: (params) => {
        params.accountName = $("#accountName").val();
        params.isUse = "0";
        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        return this.responseUtil.bsPageHandler(result, (result) => {
          result.data.rows.forEach(function (value) {
            value.CREATE_DATE = value.createDate || '';
          });
        });
      },
      height: 700,//table高度
      sortable: true,
      order: 'asc',
      sortName: 'CREATE_DATE',  //初始化默认排序
      minimumCountColumns: 3,//最少保留显示的列数量
      classes: "table table-hover",
      striped: true,//隔行变色
      mobileResponsive: true//响应式

    });
  }

  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat(value, row, index) {
    if (value == '1') {
      return '<input type="checkbox" checked>';
    }
    if (value == '0') {
      return '<input type= "checkbox">';
    }
  }

}
